'use strict';

var i18n;
var translate = angular.module('translate', []);
translate.factory('i18n', ['$http', function ($http) {
  var defaultLocale = "en";
  var languages = {};
  var currentLanguage;
  return {
    init: function (path, locale) {
      locale = locale == undefined ? defaultLocale : locale;
      if (languages[locale] != undefined) {
        currentLanguage = languages[locale];
        i18n = currentLanguage;
        return;
      }
      return $http.get(path + locale + ".json")
        .success(function (data) {
          languages[locale] = data;
          currentLanguage = data;
          i18n = currentLanguage;
        })
    },
    translate: function (word) {
      if (currentLanguage == undefined) {
        console.error("i18n is not init!");
        return;
      }
      return currentLanguage[word];
    }
  }
}]);

translate.filter("translate", ["i18n", function (i18n) {
  return function (word) {
    return i18n.translate(word);
  }
}]);
